package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLParameter;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * oracle 支持
 */
public class WindowFirstLast extends SimpleField {
    private final SimpleField target;
    private final boolean first;

    private List<OrderField> orderBy = new LinkedList<>();

    public WindowFirstLast(SimpleField target, boolean first) {
        this.target = target;
        this.first = first;
    }

    public WindowFirstLast orderBy(OrderField orderBy) {
        this.orderBy.add(orderBy);
        return this;
    }

    public WindowFirstLast orderBy(OrderField... orderBy) {
        Collections.addAll(this.orderBy, orderBy);
        return this;
    }

    @Override
    public void toConditionSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean useDefaultTableNameAlias, boolean useTablePrefix, DBDialect dialect) {
        target.toConditionSql(sb, list, useDefaultTableNameAlias, useTablePrefix, dialect);
        sb.append(" keep (dense_rank ").append(first ? "first " : "last ").append(" order by ");
        boolean b = false;
        for (OrderField orderField : orderBy) {
            if (b) {
                sb.append(',');
            }
            b = true;
            orderField.toConditionSql(sb, list, useDefaultTableNameAlias, useTablePrefix, dialect);
        }
        sb.append(')');
    }

    public WindowFunction over() {
        return new WindowFunction(this);
    }
}
